import React from 'react';
class formStore {
  constructor() {
    this.store = {};
    this.entities = [];
  }

  registerEneity = (entity) => {
    this.entities.push(entity);
    return () => {
      this.entities = this.entities.filter((item) => item !== entity);
      delete this.store[entity.props.name];
    };
  };

  getFieldValue = (name) => {
    return this.store[name];
  };
  getFieldsValue = () => {
    return this.store;
  };
  setFieldsValue = (newVals) => {
    this.store = {
      ...this.store,
      ...newVals,
    };
    this.entities.forEach((entity) => {
      const name = entity.props.name;
      if (Object.keys(newVals).includes(name)) entity.filedFourceUpdate();
    });
  };

  setFieldValue = (newValues) => {
    this.store = {
      ...this.store,
      ...newValues,
    };
  };
  validate = () => {};

  getForm = () => {
    return {
      getFieldValue: this.getFieldValue,
      getFieldsValue: this.getFieldsValue,
      setFieldsValue: this.setFieldsValue,
      setFieldValue: this.setFieldValue,
      registerEneity: this.registerEneity,
      validate: this.validate,
    };
  };
}

const useForm = () => {
  const formInstance = React.useRef();

  const store = new formStore();
  formInstance.current = store.getForm();

  return [formInstance.current];
};
export { useForm };
